package com.xiangxiangjd.config.springsecurity;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiangxiangjd.controller.helper.$;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import java.io.IOException;

/**
 * @author : Sun Chuan
 * @date : 2019/9/22 12:00
 * Description：退出成功处理器
 */
@Component
@Slf4j
public class NRSCLogoutSuccessHandler implements LogoutSuccessHandler {
    /**
     * 退出登陆url
     *      可以在yml或properties文件里通过nrsc.security.browser.signOutUrl 进行指定
     *      我指定的默认值为"/" --- 因为如果不指定一个默认的url时，配置授权那一块会报错
     */
    private ObjectMapper objectMapper = new ObjectMapper();

    private String tokenHeader = "Authorization";
    private String tokenHead = "Bearer ";

    /**
     * 这个地方应该写 删除redis 中存入的token
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */



    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {

        log.info("退出成功");

        String token = request.getHeader(tokenHeader);

     String   msg="退出成功";
        if (token==null){
            msg="请先登录！";
        }


        //如果没有指定退出成功的页面则返回前端一个json字符串
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString($.success(msg)));
    }
}
